/**
 * 
 */
package hihocoder;

import java.util.Arrays;
import java.util.Scanner;

/**
 * @author zhongfang
 *
 */
public class 皇室成员的名字 {

	public static int Char2Int(char ch) {
		switch (ch) {
		case 'I':
			return 1;
		case 'V':
			return 5;
		case 'X':
			return 10;
		case 'L':
			return 50;
		case 'C':
			return 100;
		case 'D':
			return 500;
		case 'M':
			return 1000;
		default:
			return -1;
		}
	}

	static class RoyalName implements Comparable<RoyalName> {
		String name;
		String num;
		int romeNum=-1;
		public RoyalName(String name,String num) {
			this.name=name;
			this.num=num;
//			this.romeNum=rom2int(num);
//			System.out.println(num+"  "+romeNum);
		}
		@Override
		public int compareTo(RoyalName o) {
			if (!this.name.equals(o.name) ) {
				return this.name.compareTo(o.name);
			}
			if(this.romeNum==-1){
				this.romeNum=rom2int(this.num);
			}
			if(o.romeNum==-1){
				o.romeNum=rom2int(o.num);
			}
			return this.romeNum - o.romeNum;
		}

		@Override
		public String toString() {
			return this.name+" "+this.num;
		}
		private int rom2int(String numStr) {
			int result = 0;
			int i = 0;
			int cur = -1, next = -1;
			while (i < numStr.length()) {
				if (cur == -1) {
					cur = Char2Int(numStr.charAt(i));
				}
				if (i == numStr.length() - 1) {// no next
					result+=cur;
					break;
				}
				next = Char2Int(numStr.charAt(i + 1));
				if (cur < next) {
					result+=(next-cur);
					i+=2;
					cur=-1;
				}else {
					result+=cur;
					cur=next;
					i++;
				}
			}
			return result;
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		int n=scanner.nextInt();
		scanner.nextLine();
		RoyalName[] royalNames=new RoyalName[n];
		for (int i = 0; i < n; i++) {
			String[] strings=scanner.nextLine().split(" ");
			RoyalName royalName=new RoyalName(strings[0],strings[1]);
			royalNames[i]=royalName;
		}
		Arrays.sort(royalNames);
		for (RoyalName royalName : royalNames) {
			System.out.println(royalName);
		}
	}
}
